<script setup>
import { ref, onMounted } from 'vue';
import { ElNotification } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { AddDistrictTag, FetchDistricts, RemoveDistrictTag, UpdateDistrictTag } from '@/api/index.js';

const districts = ref([]);
const newProvince = ref('');
const newCity = ref('');
const editingDistrictId = ref(null);

// 获取地域列表
const fetchDistricts = async () => {
  try {
    const response = await FetchDistricts();
    districts.value = response;
  } catch (error) {
    console.error('获取地域列表失败:', error);
    ElNotification({
      title: 'Error',
      message: '获取地域列表失败',
      type: 'error',
    });
  }
};

// 添加地域
const addDistrictTag = async () => {
  if (!newProvince.value || !newCity.value) {
    ElNotification({
      title: 'Warning',
      message: '省份和城市不能为空',
      type: 'warning',
    });
    return;
  }

  const existingDistrict = districts.value.find(
      (district) => district.province === newProvince.value && district.city === newCity.value
  );

  if (existingDistrict) {
    ElNotification({
      title: 'Warning',
      message: '该地域已存在',
      type: 'warning',
    });
    return;
  }

  try {
    const response = await AddDistrictTag({ province: newProvince.value, city: newCity.value });
    districts.value.push(response);
    newProvince.value = '';
    newCity.value = '';
    ElNotification({
      title: 'Success',
      message: '添加成功',
      type: 'success',
    });
    await fetchDistricts();
  } catch (error) {
    console.error('添加地域失败:', error);
    ElNotification({
      title: 'Error',
      message: '添加地域失败',
      type: 'error',
    });
  }
};

// 删除地域
const removeDistrictTag = async (district) => {
  try {
    await RemoveDistrictTag(district.id);
    districts.value = districts.value.filter((item) => item.id !== district.id);
    ElNotification({
      title: 'Success',
      message: '删除成功',
      type: 'success',
    });
    await fetchDistricts();
  } catch (error) {
    console.error('删除地域失败:', error);
    ElNotification({
      title: 'Error',
      message: '删除地域失败',
      type: 'error',
    });
  }
};

// 修改地域
const updateDistrictTag = async (district) => {
  editingDistrictId.value = null;
  try {
    await UpdateDistrictTag(district.id, { province: district.province, city: district.city });
    ElNotification({
      title: 'Success',
      message: '修改成功',
      type: 'success',
    });
    await fetchDistricts();
  } catch (error) {
    console.error('修改地域失败:', error);
    ElNotification({
      title: 'Error',
      message: '修改地域失败',
      type: 'error',
    });
  }
};

const editDistrict = (district) => {
  editingDistrictId.value = district.id;
};

onMounted(() => {
  fetchDistricts();
});
</script>

<template>
  <div class="district-tags">
    <h3>地域标签</h3>
    <el-tag
        v-for="district in districts"
        :key="district.id"
        type="info"
        closable
        @close="() => removeDistrictTag(district)"
    >
      <div class="district-tag-content">
        <span v-if="!editingDistrictId || editingDistrictId !== district.id" @click="editDistrict(district)">
          {{ district.province }}{{ district.city ? ` - ${district.city}` : '' }}
        </span>
        <div v-else class="district-edit-form">
          <el-input v-model="district.province" placeholder="省份" />
          <el-input v-model="district.city" placeholder="城市" @keyup.enter="() => updateDistrictTag(district)" @blur="() => updateDistrictTag(district)"/>
        </div>
      </div>
    </el-tag>
    <div class="new-tag-input">
      <el-input v-model="newProvince" placeholder="省份" />
      <el-input v-model="newCity" placeholder="城市" @keyup.enter="addDistrictTag" />
      <el-button type="primary" @click="addDistrictTag">
        <el-icon><Plus /></el-icon>
        添加
      </el-button>
    </div>
  </div>
</template>



<style scoped lang="less">
.district-tags {
  width: 600px;
  margin: 20px auto;
  text-align: left;

  h3 {
    margin-bottom: 20px;
  }

  .el-tag {
    margin-right: 10px;
    margin-bottom: 10px;
    cursor: pointer;

    .district-tag-content {
      display: flex;
      align-items: center;

      .district-edit-form {
        display: flex;

        .el-input {
          width: 100px;
          margin-right: 5px;
        }
      }
    }
  }

  .new-tag-input {
    display: flex;
    align-items: center;
    margin-top: 10px;

    .el-input {
      flex-grow: 1;
      margin-right: 10px;
      width: auto;
    }
  }
}
</style>
